<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Swoole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:action {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    public $server;
    public $setConfig = [
        'ssl_key_file' => '/usr/local/tengine/conf/cert/214136458100676.key',
        'ssl_cert_file' => '/usr/local/tengine/conf/cert/214136458100676.pem'
    ];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $arg = $this->argument('action');
        switch ($arg){
            case 'start':
                $this->info('swoole observer started');
                $this->start();
                break;
        }
    }

    private function start(){
        $this->server = new \swoole_websocket_server("0.0.0.0", 9502,SWOOLE_BASE,SWOOLE_SOCK_TCP|SWOOLE_SSL);
        $this->server->set($this->setConfig);
        $this->server->on('open', function (\swoole_websocket_server $server, $request) {
            echo "server: handshake success with fd=>{$request->fd} open_id=>{$request->header['open_id']}\n";
            $open_id = $request->header['open_id'];
            echo exec("php /data/www/yanxi.info/www.yanxi.info/artisan socket:connect $open_id $request->fd");
        });
        $this->server->on('message', function (\swoole_websocket_server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
            info('message'.$frame->data);
            $server->push($frame->fd, "this is server");
        });
        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });
        $this->server->on('request', function ($request, $response) {
            // 接收http请求从get获取message参数的值，给用户推送
            // $this->server->connections 遍历所有websocket连接用户的fd，给所有用户推送
            info('fd',$this->server->connections);
            foreach ($this->server->connections as $fd) {
                $this->server->push($fd, $request->get['message']);
            }
        });
        $this->server->start();
    }
}
